import { Component, Fragment, useEffect, useState } from "react";
import { useNavigate } from "react-router";
import { useDispatch, useSelector } from "react-redux";
import { login, clearCache, to } from '../../redux/action/common'
import { menu, staff } from '../../api/common'
import { Layout } from '@arco-design/web-react';
import { Form, Input, Button, Message, InputNumber, Spin } from '@arco-design/web-react';
import { IconUser, IconLock } from '@arco-design/web-react/icon';
import { regExpConfig } from '../../configs/regular.config'
import "@arco-design/web-react/dist/css/arco.css";
import '../../styles/login.css'
import { log } from "../../configs/common";
const Header = Layout.Header;
const Content = Layout.Content;
const FormItem = Form.Item;
export default function Login(){
    const [form] = Form.useForm();
    const dispatch = useDispatch()
    useEffect(()=>{
        dispatch(clearCache())
    }, [])
    const state = useSelector(state => state.loginState)
    const navigate = useNavigate()

    function handleSubmit(values, isCertificates, dispatch) {
        // e.preventDefault()
        if (isCertificates) {
          Message.warning('证书登录功能未开通')
          return
        }
        dispatch(
            // login有三个参数，第一个为value，包括data属性，后面两个是两个方法
            login(values, 
                (res) => {
                    sessionStorage.setItem('token', res.data.token)
                    sessionStorage.setItem('ticket', res.data.ticket)
                    menu({}, (response) => {
                    const nav = response.data.list || []
                    if (nav && nav[0]) {
                        sessionStorage.setItem('gMenuList', JSON.stringify(nav))
                        // 设置默认管理平台 desk$
                        sessionStorage.setItem('topMenuReskey', nav[0].resKey)
                        sessionStorage.setItem('leftNav', JSON.stringify(nav))
                        staff({ usercode: values.username }, (resp) => {
                            sessionStorage.setItem('role', JSON.stringify(resp.data.roles))
                            Message.success('登陆成功')
                            navigate('/', {
                                replace: false, //push模式
                                //只能写state，不能写search/params参数
                                //如果是search/params参数，直接写在路径里
                                state: {}
                            })
                        }, (r) => {
                            Message.warning(r.msg)
                        })
                    }
                    }, (response) => {
                    Message.warning(response.msg)
                    })
                },
                (res) => {
    
                    Message.warning('error')
                }
            )
        )
    }

    return(
        <div className='layout-basic-demo'>
            <Layout style={{ height: '100%' }}>
            <Header>
                <h1>My-React-App</h1>
            </Header>
            <Content>
                <div style={{margin: 'auto auto', width: '100px'}}>
                    <Spin loading={state.loading}>
                        <Form form={form} autoComplete='off' style={{ width: '280px' }} 
                              onSubmit={async (value)=>{
                                try {
                                    await form.validate();
                                    handleSubmit(value, state.isCertificates, dispatch)

                                    } catch (e) {
                                    Message.error('校验失败');
                                }
                              }}>
                            <FormItem
                                field='username'
                                required
                                rules={[
                                    {required: true, min: 4, max: 10, message: '用户名为4-10个字符',},
                                    {match: regExpConfig.policeNo, message: '账号4-10位数字或字母组成' },
                                ]}
                            >
                                <Input addBefore={<IconUser/>} placeholder='请输入用户名' allowClear/>
                            </FormItem>
                            <FormItem
                                field='password'
                                rules={[
                                    { required: true, min: 6, max: 16, message: '密码为6-16个字符',},
                                    { match: regExpConfig.pwd, message: '密码由6-16位数字或者字母组成' },
                                ]}
                            >
                                <Input.Password addBefore={<IconLock/>} placeholder='请输入密码' allowClear/>
                            </FormItem>
                            <FormItem wrapperCol={{ offset: 0 }}>
                                <Button
                                type='primary'
                                htmlType="submit"
                                style={{ marginRight: 24 }}
                                >
                                验证
                                </Button>
                                <Button
                                style={{ marginRight: 24 }}
                                onClick={() => {
                                    form.resetFields();
                                }}
                                >
                                重置
                                </Button>
                            </FormItem>
                        </Form>
                    </Spin>
                </div>
            </Content>
            </Layout>
        </div>
    )
}